/*
 * @Author: xiaosihan
 * @Date: 2022-06-14 09:48:00
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2023-04-07 21:52:03
 */

import { TextGeometry, TextGeometryParameters } from 'three/examples/jsm/geometries/TextGeometry.js';
import { Mesh, MeshStandardMaterial } from "three";
import fontContorller from "./fontController";



export type Text3DProps = {
    text?: string,
    fontType?: string,
    size?: number | undefined;
    depth?: number | undefined;
    curveSegments?: number | undefined;
    bevelEnabled?: boolean | undefined;
    bevelThickness?: number | undefined;
    bevelSize?: number | undefined;
    bevelOffset?: number | undefined;
    bevelSegments?: number | undefined;
}


// 3D文字模型
export default class Text3D extends Mesh {

    constructor(text: string = "new Text3D()") {
        super();
        this.setText({ text });
    }

    // 字体的存储路径 例如 : "http://drm.gitee.io/three-base-font/simhei/字.js"
    static path = "//www.3dkeshihua.com/three-base-font/";


    material = new MeshStandardMaterial({
        metalness: 1, // 金属度，值为0到1
        roughness: 0.5, // 粗糙度，值为0到1
    });

    // 配置
    _config: Text3DProps = {
        text: "",
        fontType: "simhei",
        size: 1,
        curveSegments: 10,
        depth: 0.1, // 文字的厚度
        bevelEnabled: true, // 斜角开启
        bevelThickness: 0.02, // 斜角厚度
        bevelSize: 0.015, // 斜角大小
        bevelOffset: 0,// 斜角偏移
        bevelSegments: 3,//斜角分段
    }

    // 设置文字
    setText(text3DProps: Text3DProps) {

        if (Object.keys(text3DProps).some(key => text3DProps[key as keyof typeof text3DProps] !== this._config[key as keyof typeof this._config])) {

            Object.assign(this._config, text3DProps);

            fontContorller.loadText({
                fontBasePath: Text3D.path,
                text: this._config.text,
                fontType: this._config.fontType,
                callback: THREEFont => {
                    this.geometry.dispose();
                    this.geometry = new TextGeometry(this._config.text || "", {
                        font: THREEFont,
                        size: this._config.size,
                        curveSegments: this._config.curveSegments,
                        depth: this._config.depth, // 文字的厚度
                        bevelEnabled: this._config.bevelEnabled, // 斜角开启
                        bevelThickness: this._config.bevelThickness, // 斜角厚度
                        bevelSize: this._config.bevelSize, // 斜角大小
                        bevelOffset: this._config.bevelOffset,// 斜角偏移
                        bevelSegments: this._config.bevelSegments,//斜角分段
                    });
                    this.geometry.center();
                    this.dispatchEvent({ type: "loaded" } as never);
                }
            })

        }

    }


}